package com.financing.controller.system;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.financing.common.CONST;
import com.financing.components.sms.Sms;
import com.financing.controller.user.UserController;
import com.financing.enums.notify.SmsNotify;
import com.financing.model.system.SmsLog;
import com.financing.model.user.User;
import com.financing.service.system.LoggerService;
import com.financing.service.user.UserService;
import com.financing.util.AES;
import com.financing.util.CheckUtils;
import com.financing.util.DateUtil;
import com.financing.util.Json;
import com.financing.util.RandomCodeUtil;
import com.financing.util.Str;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;

public class SmsLogController extends Controller {
	private UserService user = new UserService();
	private LoggerService log = new LoggerService();
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 获取短信验证码
	 */
	@Clear
	public void code() {
		int aes = getParaToInt("aes",1);
		String mobile = aes==1 ? AES.decode(getPara("mobile","")) : getPara("mobile",""); 
		if(CheckUtils.checkMoible(mobile)) {
			String type = getPara("type","reg"); 
			String dateStr = CONST.getAttr("sendCode"+mobile);
			if(Str.eq("modifyMobileNew", type) || !Str.nb(dateStr) || Long.valueOf(DateUtil.getTimeStamp())-Long.valueOf(dateStr)>=0){
				String business = "";
				String contents = "";
				String code = RandomCodeUtil.getCode();
				if(Str.eq("reg", type)){	// 注册短信验证码
					String verifyCode = getPara("verifyCode","");
					if(Str.isBlank(verifyCode) || !verifyCode.equalsIgnoreCase(CONST.getAttr("verifyCode"+mobile))) {
			    		renderJson(Json.error("图形验证码不正确！"));
			    		return ;
					}
					// 检查用户已经注册
					if(user.findByMobile(mobile)!=null){
			    		renderJson(Json.error("该手机号已注册！"));
			    		return ;
					}
					business = "注册";
					contents = Str.format(SmsNotify.REG, code, CONST.find("PLAT_PHONE"));
					CONST.removeAttr("verifyCode"+mobile);
				}else if(Str.eq("ressetPassword", type)){		// 重置/修改登陆密码短信验证码
					// 检查用户是否已注册
					if(user.findByMobile(mobile)==null){
			    		renderJson(Json.error("对不起该手机还未注册哦！"));
			    		return ;
					}
					business = "修改登陆密码";
					contents = Str.format(SmsNotify.RESSET_PASSWORD, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("modifyMobileOld", type)){		// 修改登陆手机号（旧）
					business = "修改原有登陆手机号";
					contents = Str.format(SmsNotify.MODIFY_MOBILE, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("modifyMobileNew", type)){		// 修改登陆手机号（新）
					// 检查用户已经注册 
					if(user.findByMobile(mobile)!=null){
			    		renderJson(Json.error("该手机号已注册！"));
			    		return ; 
					}
					business = "修改新登陆手机号";
					contents = Str.format(SmsNotify.MODIFY_MOBILE, code, CONST.find("PLAT_PHONE"));
				}else if(Str.eq("modifyMobileNew", type)){		// 修改登陆手机号（新）
					// 检查用户已经注册 
					if(user.findByMobile(mobile)!=null){
			    		renderJson(Json.error("该手机号已注册！"));
			    		return ; 
					}
					business = "修改新登陆手机号";
					contents = Str.format(SmsNotify.MODIFY_MOBILE, code, CONST.find("PLAT_PHONE"));
				}
				String res = Sms.send(mobile, contents);
				CONST.setAttr(type+mobile, code);
				CONST.setAttr("sendCode"+mobile, String.valueOf(new Date().getTime()+60000));
				User u = user.findByMobile(mobile);
				log.build(business+"发送短信", "手机号码："+mobile+" 验证码："+code, u!=null?u.getId():0, "user");
		        if(Str.nb(res)){
		        	logger.error("手机号："+mobile+" 内容："+contents+" 发送反馈："+res);
		    		renderJson(Json.ok("短信发送成功！"));
		        } else {
		    		renderJson(Json.error("短信发送失败！"));
		        }
			}else{
				renderJson(Json.error("操作过于频繁，请稍候再试！"));
			} 
		} else {
    		renderJson(Json.error("手机格式不正确！"));
        }
	}
	
	/**
	 *  群发短信
	 * @throws Exception 
	 */ 
	@RequiresRoles("admin")  
	public void mass() throws Exception{
		User u = getAttr("user");
		String type = getPara("type");
		String contents = getPara("contents");
		String summary = getPara("summary");
		List<User> users = new ArrayList<User>();
		Date now = new Date();
		
		if(Str.nb(type) && Str.nb(contents) && Str.nb(summary)) {
			if(Str.eq("all", type)) {
				users = User.me.find("select * from user");
			}else if(Str.eq("multiple", type)){
				for(String m : summary.split(",")) {
					User u1 = new User();
					u1.setMobile(m);
					users.add(u1);
				}
			}else if(Str.eq("sql", type)){
				users = User.me.find(summary);
			}
			int total = 0;
			int success = 0;
			int failed = 0;
			for(User t : users) {
				if(t!=null && Str.nb(t.getMobile()) && CheckUtils.checkMoible(u.getMobile())) {
					total++;
					String res = Sms.send(t.getMobile(), contents, "1012812");
					try {
				    	Document document = DocumentHelper.parseText(res);
				    	Element root = document.getRootElement();  
				        Element iterator = root.element("State");
				        if(Str.eq("0", iterator.getText())) {
				        	success++;
				        }else {
				        	failed++;
				        }
					} catch (DocumentException e) {
						e.printStackTrace();
					}
				} 
			}
			
			SmsLog sl = new SmsLog();
			sl.setType(type);
			sl.setContents(contents);
			sl.setSummary(summary);
			sl.setUserId(u.getId());
			sl.setRealName(u.getRealName());
			sl.setCreateTime(now);
			sl.setSuccess(success);
			sl.setFailed(failed);
			sl.setTotal(total);
			sl.save();
			
			renderJson(Json.ok("短信群发成功！"));
		} else {
    		renderJson(Json.error("发送参数不正确！"));
        }
	}	
	
	public static void main(String[] args) {
		try {
	    	Document document = DocumentHelper.parseText("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" + 
	    			"<CSubmitState xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://tempuri.org/\">\r\n" + 
	    			"  <State>0</State>\r\n" + 
	    			"  <MsgID>1711240856246673963</MsgID>\r\n" + 
	    			"  <MsgState>提交成功</MsgState>\r\n" + 
	    			"  <Reserve>2</Reserve>\r\n" + 
	    			"</CSubmitState>");
	    	Element root = document.getRootElement();  
	    	@SuppressWarnings("unchecked")
			List<Attribute> list = root.attributes();  
	        //遍历属性节点  
	        for(Attribute attribute : list){  
	            System.out.println("属性"+attribute.getName() +":" + attribute.getValue());  
	        }  
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			
		}
    }
}
 